package com.lijian.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lijian.mapper.UserMapper;
import com.lijian.pojo.User;
import com.lijian.pojo.UserResult;
import com.lijian.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/findAll")
    public UserResult findAll(@RequestParam Integer page, @RequestParam Integer limit){
        IPage<User> userIPage = userMapper.selectPage(new Page<>(page, limit), null);

        Integer total = Math.toIntExact(userIPage.getTotal());
        return new UserResult(0, "成功", total, userIPage.getRecords());
    }

    @GetMapping("/findById/{id}")
    public User findById(@PathVariable Integer id){
        return userMapper.selectById(id);
    }

    @PostMapping("/save")
    public void save(@RequestBody User user){
        user.setPassword(MD5Utils.code(user.getPassword()));
        user.setRegisterdate(new Date());
        userMapper.insert(user);
    }

    @PutMapping("/update")
    public void update(@RequestBody User user){
        userMapper.updateById(user);
    }

    @DeleteMapping("deleteById/{id}")
    public void delete(@PathVariable Integer id){
        userMapper.deleteById(id);
    }
}
